<template>
  <div class="card upload-section" style="width: 98%;margin: 10px;">
    <h3><i class="fas fa-table"></i> 分析数据</h3>
    <div v-if="csvRows.length > 0">
      <div class="table-responsive">
        <table class="table table-bordered data-table">
          <thead>
            <tr>
              <th>行为类别</th>
              <th v-for="(row, idx) in csvRows" :key="idx">第{{ idx + 1 }}组</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="col in csvColumns" :key="col">
              <td>{{ col }}</td>
              <td v-for="(row, idx) in csvRows" :key="idx">{{ row[col] }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div v-else>暂无分析数据，请先分析视频</div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'DataPanel',
  data() {
    return {
      account: localStorage.getItem('account') || '',
      videoName: localStorage.getItem('currentAnalyzedVideo') || '',
      allResults: [],
      csvColumns: [],
      csvRows: []
    }
  },
  mounted() {
    this.fetchResults();
  },
  watch: {
    videoName() {
      this.fetchResults();
    }
  },
  methods: {
    fetchResults() {
      const account = localStorage.getItem('account');
      if (!account) return; // 没有登录不请求
      axios.get('/api/get-results/' + account)
        .then(res => {
          this.allResults = res.data.results || [];
          // 找到当前分析视频的csv_path
          const csvItem = this.allResults.find(item =>
            item.video_name === this.videoName && item.csv_path
          );
          if (csvItem && csvItem.csv_path) {
            axios.get(csvItem.csv_path).then(csvRes => {
              const csvContent = typeof csvRes.data === 'string' ? csvRes.data : csvRes.data;
              const lines = csvContent.split('\n').filter(Boolean);
              this.csvColumns = lines[0].split(',');
              this.csvRows = lines.slice(1).map(line => {
                const values = line.split(',');
                const row = {};
                this.csvColumns.forEach((col, idx) => row[col] = values[idx]);
                return row;
              });
            });
          } else {
            this.csvColumns = [];
            this.csvRows = [];
          }
        });
    }
  }
}
</script>

<style scoped>
.table-responsive {
  overflow-x: auto;
}
.data-table {
  min-width: 500px;
  background: #f8fafc;
}
.data-table th,
.data-table td {
  border: 1px solid #e3e6ea;
  padding: 10px 8px;
  text-align: center;
  font-size: 15px;
  vertical-align: middle;
  white-space: nowrap;
}
.data-table th {
  background: #e3f0fa;
  color: #1a2b3c;
  font-weight: 600;
}
</style>